package com.demo.controller;

import com.demo.entity.Student;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * @author zhiqiang
 */
@Slf4j
@RestController
@RequestMapping("/testController")
public class ZhuJieController {

    /**
     * 语法： @PathVariable("id") String sid
     * 用于接收请求路径中占位符的值
     * 注解括号内的参数名取值必须和请求路径中的参数名一致
     *
     * @param sid
     * @param name
     * @return
     */
    @GetMapping("/test1/{id}/{name}")
//    @PostMapping("/test1/{id}/{name}")
    public Student buildStudent(@PathVariable("id") String sid, @PathVariable("name") String name) {
        Student student = new Student();
        student.setId(sid);
        student.setName(name);
        return student;
    }


    /**
     * 语法：@RequestParam(value="参数名",required="true/false",defaultValue="")
     * value：参数名，指定参数名之后请求参数名必须与该参数名保持一致
     * required：是否包含该参数，默认为true，表示该请求路径中必须包含该参数，如果不包含就报错。
     * defaultValue：默认参数值，如果设置了该值，required=true将失效，自动为false,如果没有传该参数，就使用默认值，传参数则使用请求参数
     *
     * @return
     */
    @GetMapping("/test2")
//    @PostMapping("/test2")
    public Student buildStudent2(@RequestParam(value = "name", required = true, defaultValue = "张三") String sname) {
        Student student = new Student();
        student.setName(sname);
        return student;
    }

    /**
     * 语法：@RequestBody(required = true) required默认为true
     * 用于接收前端传递的json字符串
     *
     * @param jsonString
     * @return
     */
//      @GetMapping("/test3")
    @PostMapping("/test3")
    public Student buildStudent3(@RequestBody(required = true) String jsonString) {
        Student student = new Student();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            student = objectMapper.readValue(jsonString, student.getClass());
        } catch (JsonProcessingException e) {
            log.error("json字符串【{}】转对象失败", jsonString, e);
        }
        return student;
    }
}
